package com.wangsb.controller;

import com.wangsb.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 * @author: shenbing.wang@hand-china
 * @date: 2021年02月21日 10:56
 */
@Controller
@RequestMapping("/converter")
public class ConverterController {

    @GetMapping("/test")
    public String converter01(User user) {
        System.out.println("user = " + user);
        return "show";
    }

    @PostMapping("/addUser")
    public String addUser(@Valid User user, BindingResult result, Model model) {
        System.out.println("result   = " + result.getErrorCount());
        if (result.hasErrors()) {
            Map<String, String> map = new HashMap<>(16);
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                map.put(fieldError.getField(), fieldError.getDefaultMessage());
                model.addAttribute("errors", map);
            }
            return "user/add";
        }
        System.out.println("user = " + user);
        return "show";
    }
}
